from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.permissions import  IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from comments.models import Spit
from comments.myserializer import SpitSerializer


# 余海平 -- 6.1 吐槽列表 GET /spit/
class SpitListView(ModelViewSet):
    serializer_class = SpitSerializer
    queryset = Spit.objects.all().order_by("-publishtime")

    def perform_authentication(self, request):
        pass

    # 余海平 -- 6.1 吐槽列表 GET /spit/
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(parent=None)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

        # 余海平 -- 6.4、发布吐槽  POST /spit/
    def create(self, request, *args, **kwargs):
        print(request.data)
        parent = request.data.get("parent")
        user = self.request.user
        t = user.is_authenticated
        if not parent:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid()
            serializer.save()
            return Response(serializer.data)
        else:
            if t:
                obj = self.get_queryset().get(id=parent)
                obj.comment += 1
                obj.save()
                serializer = self.get_serializer(data=request.data)
                serializer.is_valid()
                serializer.save()
                return Response(serializer.data)
            else:
                return Response({"message": "未登录", "success": False}, status=status.HTTP_403_FORBIDDEN)

    # 余海平 -- 6.6、获取吐槽评论  GET   /spit/{id}/children/
    def children(self, request, *args, **kwargs):
        obj = self.get_object()
        obj.visits += 1
        obj.save()
        objs = Spit.objects.filter(parent_id=obj.id)
        user = self.request.user
        spit_list = []
        if user and user.is_authenticated:
            redis_conn = get_redis_connection("spit")
            for spit in objs:
                collect = redis_conn.hget('collect_%s' % user.id, obj.id)
                thumbup = redis_conn.hget('thumbup_%s' % user.id, obj.id)
                if collect:
                    spit.collected = True
                if thumbup:
                    spit.hasthumbup = True
                spit_list.append(spit)
        else:
            spit_list = objs
        serialzier = self.get_serializer(spit_list, many=True)


        return Response(serialzier.data)


class SpitViewSet(ModelViewSet):
    serializer_class = SpitSerializer
    queryset = Spit.objects.all().order_by("-publishtime")
    permission_classes = [IsAuthenticated]

    # 余海平 -- 6.2 收藏或取消收藏  PUT  /spit/{id}/collect/
    def collected(self, request, *args, **kwargs):
        user = self.request.user
        if not user.is_authenticated:
            return Response({"message": "未登录", "success": False}, status=status.HTTP_403_FORBIDDEN)
        obj = self.get_object()
        pk = obj.id
        redis_conn = get_redis_connection("spit")
        collect = redis_conn.hget('collect_%s' % user.id, pk)
        if collect:
            redis_conn.hdel('collect_%s' % user.id, pk)
            obj.collected = False
            obj.save()
            return JsonResponse({"message": "取消收藏成功", "success": True})
        else:
            redis_conn.hset('collect_%s' % user.id, pk, 1)
            obj.collected = True
            obj.save()
            return JsonResponse({"message": "收藏成功", "success": True})

    # 余海平 -- 6.3 点赞或取消点赞 PUT /spit/{id}/updatethumbup/
    def updatethumbup(self, request, *args, **kwargs):
        user = self.request.user
        if not user.is_authenticated:
            return Response({"message": "未登录", "success": False}, status=status.HTTP_403_FORBIDDEN)
        obj = self.get_object()
        pk = obj.id
        obj = Spit.objects.get(id=pk)
        redis_conn = get_redis_connection("spit")
        thumbup = redis_conn.hget('thumbup_%s' % user.id, pk)
        if thumbup:
            redis_conn.hdel('thumbup_%s' % user.id, pk)
            obj.thumbup -= 1
            obj.save()
            return JsonResponse({"message": "取消点赞成功", "success": True})
        else:
            redis_conn.hset('thumbup_%s' % user.id, pk, 1)
            obj.thumbup += 1
            obj.save()
            return JsonResponse({"message": "点赞成功", "success": True})














